package oktx.narayana;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.transaction.jta.NarayanaJtaConfiguration;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;

/**
 * Created by huangdachao on 2018/6/5 17:00.
 */
@Configuration
@AutoConfigureBefore(NarayanaJtaConfiguration.class)
@Import(NarayanaXADataSourceWrapper.class)
public class NarayanaAutoConfig implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOG = LoggerFactory.getLogger(NarayanaAutoConfig.class);

    @Bean
    @ConditionalOnMissingBean(ThreadPoolTaskScheduler.class)
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(2);
        return threadPoolTaskScheduler;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        threadPoolTaskScheduler().scheduleAtFixedRate(() -> {
            long tm = System.currentTimeMillis();
            NarayanaConnectionManager.getConnections().forEach(c -> {
                long idle = (tm - c.getLastUseTime().getTime()) / 1000;
                if (idle > 1800) {
                    c.closeCurrentConnection();
                    LOG.info("移出数据库连接，连接已空闲{}秒", idle);
                }
            });
        }, new Date(new Date().getTime() + 300_000), 600_000); // 第10分钟执行一次，初次延迟5分钟
    }
}
